package com.qjjbmt.zhq_blog_admin.controller;

import com.qjjbmt.zhq_blog_admin.pojo.Reply;
import com.qjjbmt.zhq_blog_admin.pojo.User;
import com.qjjbmt.zhq_blog_admin.service.impl.CommentServiceImpl;
import com.qjjbmt.zhq_blog_admin.service.impl.ReplyServiceImpl;
import com.qjjbmt.zhq_blog_admin.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.Collection;

@Controller
public class ReplyController {

    UserServiceImpl userService;
    CommentServiceImpl commentService;
    ReplyServiceImpl replyService;

    public ReplyController(CommentServiceImpl commentService, UserServiceImpl userService,
                           ReplyServiceImpl replyService){
        this.commentService = commentService;
        this.userService = userService;
        this.replyService = replyService;
    }

    /*
    查询所有回复
     */
    @RequestMapping("/replys")
    public String list(Model model){
        Collection<Reply> replys = replyService.list();
        model.addAttribute("replys",replys);
        return "reply/reply_list";
    }

    /*
    跳转到添加页面
     */
    @GetMapping("/addReply")
    public String toAddReplyPage(Model model){
        model.addAttribute("users",userService.list());
        model.addAttribute("comments",commentService.list());
        return "reply/add";
    }

    /*
   添加回复，然后刷新列表
    */
    @PostMapping("/addReply")
    public String addReply(Reply reply){
        User user = userService.getById(reply.getNickName());
        reply.setNickName(user.getUsername());
        reply.setStatus("01");

        LocalDateTime dateTime = LocalDateTime.now();
        reply.setCreateDate(dateTime);

        replyService.save(reply);
        return "redirect:/replys";
    }

    /*
    根据id查询回复，然后跳转到修改页面并展示
     */
    @GetMapping("/reply/{id}")
    public String toUpdateReplyPage(@PathVariable("id")Integer id, Model model){
        //查出原来的数据
        model.addAttribute("reply",replyService.getById(id));
        model.addAttribute("comments",commentService.list());
        return "reply/update";
    }

    /*
    保存管理员的修改
     */
    @RequestMapping("/updateReply")
    public String updateReply(Reply reply){
        replyService.updateById(reply);
        return "redirect:/replys";
    }

    /*
    根据id删除回复，然后刷新列表
     */
    @GetMapping("/delReply/{id}")
    public String deleteReply(@PathVariable("id") Integer id){
        replyService.removeById(id);
        return "redirect:/replys";
    }

}
